# 中值滤波、高斯滤波
# 腐蚀膨胀
import cv2
import os
import numpy as np
from PIL import Image

directory_name='D:/whitebubble/machinelearning/preprocessing/img_test'
savedir='D:/whitebubble/machinelearning/preprocessing/img_filter'

# 创建保存文件夹
isExists = os.path.exists(savedir)
if not isExists:
    os.mkdir(savedir)

for filename in os.listdir(directory_name):
    #img is used to store the image data
    img = cv2.imread(directory_name + "/" + filename)
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 滤波去噪
    lbimg_array = cv2.medianBlur(gray_img, 3) # 中值滤波
    # lbimg_array = cv2.GaussianBlur(gray_img,3) # 高斯滤波

    # 开运算
    kernel = np.ones((3, 3), dtype=np.uint8)
    opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel, 1)
    #ss = np.hstack((img, opening))

    # 保存结果
    lbimg = Image.fromarray(lbimg_array) #lbimg_array数据类型是array lbimg数据类型是image
    lbimg.save(savedir+'/'+filename)

    #cv2.imshow('src', img)
    cv2.imshow('dst', lbimg_array)
    cv2.imshow('open', opening)
    cv2.waitKey()

